<!-- Page de détails d'un sous-domaine -->
<template>
  <main>
    <LayoutContainer>
      <UiLoadingPanel v-if="pending" />
      <div v-else>
        <div>
          {{ $t('youRegisteredTheFollowingSubdomain')}} :
        </div>

        <div class="pa-8">
          <b>{{ subdomain.subdomain }}</b>
          <span class="text-on-neutral">.opentalent.fr</span>
        </div>

        <div>
          <div v-if="subdomain.active">
            <v-icon class="text-success icon small mr-2">
              fa-solid fa-check
            </v-icon>
            {{ $t('subdomainIsCurrentlyActive') }}
          </div>
          <div v-else>
            {{ $t('doYouWantToActivateThisSubdomain') }} ?
          </div>
        </div>

        <div class="mt-6 d-flex flex-row">
          <v-btn class="mr-12" @click="quit">
            {{ $t('back') }}
          </v-btn>
          <div v-if="!subdomain.active">
            <v-btn color="primary" @click="activateAndQuit" >
              {{ $t('activate') }}
            </v-btn>
          </div>
        </div>
      </div>
    </LayoutContainer>
  </main>
</template>

<script setup lang="ts">
  import Subdomain from "~/models/Organization/Subdomain";
  import {useEntityFetch} from "~/composables/data/useEntityFetch";
  import {useOrganizationProfileStore} from "~/stores/organizationProfile";
  import {useEntityManager} from "~/composables/data/useEntityManager";
  import {usePageStore} from "~/stores/page";
  import {TYPE_ALERT} from "~/types/enum/enums";
  import {useRefreshProfile} from "~/composables/data/useRefreshProfile";

  const { em } = useEntityManager()
  const { fetch } = useEntityFetch()
  const organizationProfile = useOrganizationProfileStore()

  const router = useRouter()
  const route = useRoute()

  const { refreshProfile } = useRefreshProfile()

  if (!route.params.id || isNaN(route.params.id as any)) {
    throw new Error('no id found')
  }
  const id: number = parseInt(route.params.id as string)

  const { data: subdomain, pending } = fetch(Subdomain, id)

  const activationPending: Ref<boolean> = ref(false)

  const pageStore = usePageStore()

  const activateAndQuit = async () => {
    activationPending.value = true
    pageStore.loading = true
    await em.patch(Subdomain, id, { active: true} )
    await refreshProfile()
    usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['subdomain_activated_and_available_in_a_few_minutes'])
    quit()
  }

  const quit = () => {
    router.push('/parameters/website')
    activationPending.value = false
    pageStore.loading = false
  }


</script>
